"""
应用配置管理
"""
import os
from typing import List, Optional
from pydantic import Field
from pydantic_settings import BaseSettings
from pydantic import field_validator


class Settings(BaseSettings):
    """应用配置类"""
    
    # 应用基本信息
    APP_NAME: str = "音频处理API"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = False
    
    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    
    # 数据库配置 - MySQL
    DATABASE_URL: Optional[str] = None
    MYSQL_HOST: str = Field(default="localhost", env="MYSQL_HOST")
    MYSQL_PORT: int = Field(default=3306, env="MYSQL_PORT")
    MYSQL_USER: str = Field(default="root", env="MYSQL_USER")
    MYSQL_PASSWORD: str = Field(default="123456", env="MYSQL_PASSWORD")  # 可通过环境变量 MYSQL_PASSWORD 注入
    MYSQL_DATABASE: str = Field(default="audio_processing", env="MYSQL_DATABASE")
    
    # 音频处理配置
    MAX_FILE_SIZE: int = 52428800  # 50MB
    ALLOWED_AUDIO_TYPES: List[str] = [
        "audio/mpeg", "audio/wav", "audio/mp3", 
        "audio/x-wav", "audio/wave", "audio/mp4"
    ]
    UPLOAD_DIR: str = "static/uploads"
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "logs/app.log"
    
    # CORS配置
    BACKEND_CORS_ORIGINS: List[str] = ["*"]

    # 腾讯云COS配置
    COS_REGION: str = Field(default="ap-shanghai", env="COS_REGION")
    COS_BUCKET_NAME: str = Field(default="7072-prod-9g0122jya167263e-1379500235", env="COS_BUCKET_NAME")
    COS_SECRET_ID: str = Field(default="", env="COS_SECRET_ID")
    COS_SECRET_KEY: str = Field(default="", env="COS_SECRET_KEY")

    
    @field_validator("BACKEND_CORS_ORIGINS", mode="before")
    @classmethod
    def assemble_cors_origins(cls, v):
        if isinstance(v, str):
            return [i.strip() for i in v.split(",")]
        return v
    
    @property
    def database_url(self) -> str:
        """构建同步数据库URL"""
        if self.DATABASE_URL:
            return self.DATABASE_URL
        return (
            f"mysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}"
            f"@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"
        )
    
    @property
    def database_async_url(self) -> str:
        """构建异步数据库URL"""
        if self.DATABASE_URL:
            # 如果提供了完整URL，转换为异步URL
            return self.DATABASE_URL.replace("mysql://", "mysql+aiomysql://")
        return (
            f"mysql+aiomysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}"
            f"@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"
        )
    
    class Config:
        env_file = ".env" if os.path.exists(".env") else None
        case_sensitive = True


# 创建全局配置实例
settings = Settings()


def get_settings() -> Settings:
    """获取配置实例"""
    return settings
